package org.example.config;

import org.example.model.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null){
            User user = (User) session.getAttribute("user");
            if(user != null){
                //已经登录，允许访问
                return true;
            }
        }
        //未登录，不允许访问
        //先获取我们的请求路径，根据前端还是后端请求来决定是返回401还是重定向到登录页面
        String path = request.getServletPath();
        if(path.startsWith("api")){
            response.setStatus(401);
        }else{
            response.sendRedirect("/login.html");
        }

        return false;
    }
}
